package org.jeecg.modules.demo.yy.Component;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.jeecg.modules.demo.yy.Model.BaiduWenxinYiYanQA;
import org.jeecg.modules.demo.yy.Model.BaiduWenxinYiYanToken;
import org.jeecg.modules.demo.yy.entity.YyhzQa;
import org.jeecg.modules.demo.yy.mapper.YyhzQaMapper;
import org.jeecg.modules.demo.yy.util.UserUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 创建WebSocket服务器监听盒子传递的问题
 */
@Component
public class MyWebSocketServerComponent {

    private WebSocketServer webSocketServer;
    @Autowired
    private YyhzQaMapper yyhzQaMapper;
    @Autowired
    private UserUtil userUtil;
    @PostConstruct
    public void startWebSocketServer() {
        //设定WebSocket端口
        int port = 7789;
        InetSocketAddress address = new InetSocketAddress(port);
        webSocketServer = new WebSocketServer(address) {
            @Override
            public void onOpen(WebSocket conn, ClientHandshake handshake) {
                System.out.println("连接成功! " + conn.getRemoteSocketAddress());
            }

            @Override
            public void onClose(WebSocket conn, int code, String reason, boolean remote) {
                System.out.println("连接关闭: " + reason);
            }

            @Override
            public void onMessage(WebSocket conn, String message) {
                System.out.println("Received message: " + message);
                //截取盒子传过来的字符串
                String content = message.substring(message.indexOf(":") + 1).replaceAll("[^\\u4E00-\\u9FA5]", "");
                boolean isChinese = content.matches("[\\u4E00-\\u9FA5]+");
                if (isChinese) {
                    //写入数据库
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String currentTime = sdf.format(new Date());
                    YyhzQa yyhzQa = new YyhzQa();
                    yyhzQa.setWt(content);
                    yyhzQa.setSj(currentTime);

                    try {
                        //调用方法获取token
                        String token = BaiduWenxinYiYanToken.getWenxinToken();
                        //调用大模型方法获取回答
                        String response = BaiduWenxinYiYanQA.wenxinyiyanApi(token, content);
                        //解析回答字符串
                        JsonParser parser = new JsonParser();
                        JsonObject jsonObject = parser.parse(response).getAsJsonObject();
                        String result = jsonObject.get("result").getAsString();
                        //传回盒子,让盒子读出来(必须加play,不加盒子不读,也可以加sleep,sleep是读完回答之后自动进入休眠状态)
                        conn.send("play" + result);

                        // 异步存储到数据库(怀疑写入数据库操作会拖慢回答速度,实测没影响,用不用异步都行)
                        ExecutorService executor = Executors.newCachedThreadPool();
                        executor.submit(() -> {
                            yyhzQa.setHd(result);
                            yyhzQa.setCreateBy("语音提问");
                            yyhzQaMapper.insert(yyhzQa);
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println();
                }
            }

            @Override
            public void onError(WebSocket conn, Exception ex) {
                ex.printStackTrace();
            }

            @Override
            public void onStart() {
                System.out.println("WebSocket服务器已启动并监听端口: " + getPort());
            }
        };
        webSocketServer.start();
    }

    @PreDestroy
    public void stopWebSocketServer() throws InterruptedException {
        if (webSocketServer != null) {
            webSocketServer.stop(1000); // 等待1秒以关闭连接
            webSocketServer = null;
        }
    }
}
